package com.woniuxy.goods.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.core.util.StateNum;
import com.woniuxy.goods.dto.AttrConfigDto;
import com.woniuxy.goods.dto.AttrGroupDto;
import com.woniuxy.goods.dto.AttrInfoDto;
import com.woniuxy.goods.dto.GroupTypeDto;
import com.woniuxy.goods.entity.AttributeGroup;
import com.woniuxy.goods.mapper.AttributeGroupMapper;
import com.woniuxy.goods.param.*;
import com.woniuxy.goods.service.AttributeConfigService;
import com.woniuxy.goods.service.AttributeGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.goods.service.GroupTypeService;
import com.woniuxy.web.util.ConvertUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 * 属性组管理服务层实现类
 * @author ...
 * @since 2024年05月22日
 */
@Service
public class AttributeGroupServiceImpl extends ServiceImpl<AttributeGroupMapper, AttributeGroup> implements AttributeGroupService {
    /**
     * 属性组属性配置服务层接口
     */
    @Resource
    private AttributeConfigService attrConfigService;
    /**
     * 属性组类别配置服务层接口
     */
    @Resource
    private GroupTypeService groupTypeService;

    /**
     * 新增属性组
     * @param param 新增属性组参数对象
     * @return 属性组信息
     * @throws Exception
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public AttrGroupDto addAttrGroup(AddGroupParam param) throws Exception {
        QueryWrapper<AttributeGroup> wrapper = new QueryWrapper<>();
        wrapper.eq("group_name",param.getGroupName());
        AttributeGroup selectOne = getOne(wrapper);
        if (ObjectUtil.isNotEmpty(selectOne)) throw new Exception("该名称已存在");
        AttributeGroup group = new AttributeGroup();
        group.setGroupName(param.getGroupName());
        group.setGroupState(StateNum.ATTR_GROUP_STATE_NORMAL);
        List<AttributeGroup> groups = list();
        int size = groups.size()+1;
        String no = Integer.toString(size);
        if (no.length()<3){
            no = String.format("%03d",size);
        }
        group.setGroupOrder(no);
        save(group);
        AddAttrConfigParam configParam = new AddAttrConfigParam();
        configParam.setGroupId(group.getGroupId());
        configParam.setAttributeId(param.getAttributeId());
        attrConfigService.addAttrConfig(configParam);
        return BeanUtil.toBean(group,AttrGroupDto.class);
    }

    /**
     * 删除属性组
     * @param groupId 属性组id
     * @return
     * @throws Exception
     */
    @Override
    public void delAttrGroup(Integer groupId) {
        removeById(groupId);
        //删除属性组绑定里的对应记录
        attrConfigService.delConfigByGroupId(groupId);
    }

    /**
     * 修改属性组
     * @param param 修改属性组对象
     * @return 属性组信息
     * @throws Exception
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public AttrGroupDto updateAttrGroup(UpdateAttrGroupParam param) throws Exception {
        AttributeGroup group = getById(param.getGroupId());
        if (group==null) throw new Exception("该属性组不存在");
        QueryWrapper<AttributeGroup> wrapper = new QueryWrapper<>();
        wrapper.eq("group_name",param.getGroupName());
        AttributeGroup selectOne = getOne(wrapper);
        if (ObjectUtil.isNotEmpty(selectOne)&&selectOne.getGroupId()!=param.getGroupId()) throw new Exception("该名称已存在");
        if (param.getGroupState()!=StateNum.ATTR_GROUP_STATE_DISABLED&&param.getGroupState()!=StateNum.ATTR_GROUP_STATE_NORMAL){
            throw new Exception("状态异常");
        }
        AttributeGroup bean = BeanUtil.toBean(param, AttributeGroup.class);
        updateById(bean);
        if(ObjectUtils.isNotEmpty(param.getAttributeId())){
            AddAttrConfigParam configParam = new AddAttrConfigParam();
            configParam.setGroupId(group.getGroupId());
            configParam.setAttributeId(param.getAttributeId());
            attrConfigService.updateConfigByGroupId(configParam);
        }
        return findAttrGroupById(bean.getGroupId());
    }

    /**
     * 修改属性组状态
     * @param param 修改属性组对象
     * @return 属性组信息
     * @throws Exception
     */
    @Override
    public List<AttrGroupDto> updateAttrGroupByIds(UpdateAttrGroupParam param) throws Exception {
        UpdateWrapper<AttributeGroup> wrapper = new UpdateWrapper<>();
        wrapper.in("group_id",param.getGroupIds());
        wrapper.set("group_state",param.getGroupState());
        update(wrapper);
        QueryWrapper<AttributeGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("group_id",param.getGroupIds());
        List<AttributeGroup> list = list(wrapper);
        List<AttrGroupDto> dtoList = new ArrayList<>();
        for (AttributeGroup group : list) {
            AttrGroupDto dto = findAttrGroupById(group.getGroupId());
            dtoList.add(dto);
        }
        return dtoList;
    }

    /**
     * 根据id查询属性组
     * @param groupId 属性组id
     * @return 属性组信息
     * @throws Exception
     */
    @Override
    public AttrGroupDto findAttrGroupById(Integer groupId) throws Exception {
        AttributeGroup group = getById(groupId);
        AttrGroupDto record = BeanUtil.toBean(group, AttrGroupDto.class);
        return record;
    }

    /**
     * 根据ids查询属性组
     * @param groupIds 属性组id集合
     * @return 属性组信息集合
     * @throws Exception
     */
    @Override
    public List<AttrGroupDto> findAttrGroupByIds(Set<Integer> groupIds) throws Exception {
        QueryWrapper<AttributeGroup> wrapper = new QueryWrapper<>();
        wrapper.in("group_id",groupIds);
        wrapper.eq("group_state",StateNum.ATTR_GROUP_STATE_NORMAL);
        List<AttributeGroup> groups = list(wrapper);
        List<AttrGroupDto> dtoList = new ArrayList<>();
        for (AttributeGroup group : groups) {
            AttrGroupDto record = findAttrGroupById(group.getGroupId());
            dtoList.add(record);
        }
        return dtoList;
    }

    /**
     * 分页查询属性组
     * @param param 属性组名称
     * @return 属性组分页对象
     * @throws Exception
     */
    @Override
    public IPage<AttrGroupDto> findGroupPage(FindConfigPageParam param) throws Exception {
        Page<AttributeGroup> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<AttributeGroup> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("group_order");
        if (ObjectUtil.isNotEmpty(param.getGroupName())){
            wrapper.like("group_name",param.getGroupName());
        }
        page(page,wrapper);
        IPage<AttrGroupDto> iPage = page.convert(v -> {
            AttrGroupDto groupDto = new AttrGroupDto();
            BeanUtil.copyProperties(v, groupDto);
            return groupDto;
        });
        List<AttrGroupDto> newRecords = new ArrayList<>();
        for (AttrGroupDto record : iPage.getRecords()) {
            List<AttrConfigDto> configDtoList = attrConfigService.findConfigByGroupId(record.getGroupId());
            List<AttrInfoDto> infoDtoList = configDtoList.stream().map(o -> o.getInfoDto()).collect(Collectors.toList());
            record.setInfoList(infoDtoList);
            List<GroupTypeDto> typeDtoList = groupTypeService.findGroupTypeByGroupId(record.getGroupId());
            Set<String> collect = typeDtoList.stream().map(o -> o.getCatDto().getCatName()).collect(Collectors.toSet());
            String catString = "暂无";
            for (String s : collect) {
                if (s==null){
                    break;
                }
                System.out.println(s);
                if(catString.equals("暂无")){
                    catString = "";
                }
                catString+=s+",";
                System.out.println(catString);
            }
            if (catString.endsWith(",")){catString = catString.substring(0, catString.length() - 1);}
            System.out.println(catString);
            record.setCatString(catString);
            newRecords.add(record);
        }
        iPage.setRecords(newRecords);
        return iPage;
    }
}
